package com.yunshipei.manager;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.yunshipei.base.EnterBaseSubscriber;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.core.download.YspDownload;
import com.yunshipei.core.model.XDownloadModel;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.download.DownloadAppService;
import com.yunshipei.model.Update;
import com.yunshipei.parser.UpdateParser;
import com.yunshipei.ui.dialog.CommonDialog;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONObject;

public class UpdateManager {

    private Update mUpdate;

    private Context mContext;

    private boolean isShow = false;

    private WaitDialog waitDialog;

    private boolean isHomeCheck = false;

    private static final String PARAM_IGNORE_UPDATE = "ignore_update_version_name";

    public static final String EXTRA_DOWNLOAD_URL = "APK_DOWNLOAD_URL";
    public static final String EXTRA_DOWNLOAD_APP_VERSION_NAME = "VERSION_NAME";

    private void parseUpdate(JSONObject response) {
        Log.e("response",response.toString());
        UpdateParser updateParser = new UpdateParser();
        updateParser.parseContent(response);
        mUpdate = updateParser.getUpdate();
    }

    public UpdateManager(Context context, boolean isShow) {
        this.mContext = context;
        this.isShow = isShow;
    }

    public UpdateManager(Context context, boolean isShow, boolean isHomeCheck) {
        this(context, isShow);
        this.isHomeCheck = isHomeCheck;
    }

    private boolean haveNew() {
        if (this.mUpdate == null || !mUpdate.isEnableUpdate()) {
            return false;
        }
        boolean haveNew = false;
        String versionName = BaseUtil.getVersionName().trim();
        String newVersionName = mUpdate.getVersionName().trim();
        if (!TextUtils.isEmpty(newVersionName) && !TextUtils.isEmpty(versionName)) {
            //比较版本名称的大小
            String[] currentVersionArray = versionName.split("\\.");
            String[] newVersionArray = newVersionName.split("\\.");
            if (currentVersionArray.length == newVersionArray.length) {
                for (int i = 0; i < currentVersionArray.length; i++) {
                    int currentItem = Integer.parseInt(currentVersionArray[i]);
                    int newItem = Integer.parseInt(newVersionArray[i]);
                    //如果相等，则比较下一位
                    if (currentItem == newItem) continue;
                    haveNew = (newItem > currentItem);
                    break;
                }
            }
        }
        return haveNew;
    }

    public void checkUpdate(String companyID) {
        if (isShow) {
            showCheckDialog();
        }
        HttpMethods.getInstance().checkUpdate(companyID, new EnterBaseSubscriber() {

            @Override
            public void onSuccess(JSONObject data) {
                hideCheckDialog();
                parseUpdate(data);
                onFinishCheck();
            }

            @Override
            public void onFailure(String errorMessage) {
                hideCheckDialog();
                if (isShow) {
                    showFailureDialog(errorMessage);
                }
            }
        });
    }

    private void onFinishCheck() {
        if (haveNew()) {
            SharedPreferences sp = YspPreferences.getInstance().getSharedPreferences();
            String ignoreVersionName = sp.getString(PARAM_IGNORE_UPDATE, "");
            if (isHomeCheck && !TextUtils.isEmpty(ignoreVersionName) && ignoreVersionName.equals(mUpdate.getVersionName())) {
                return;
            }
            showUpdateInfo();
        } else {
            if (isShow) {
                showLatestDialog();
            }
        }
    }

    private void showCheckDialog() {
        if (waitDialog == null) {
            waitDialog = DialogHelper.getWaitDialog(mContext, "正在获取新版本信息...");
        }
        waitDialog.show();
    }

    private void hideCheckDialog() {
        if (waitDialog != null) {
            waitDialog.dismiss();
        }
    }

    private void showUpdateInfo() {
        if (mUpdate == null) {
            return;
        }
        final SharedPreferences sp = YspPreferences.getInstance().getSharedPreferences();
        final CommonDialog dialog = DialogHelper.getCancelableCommonDialog(mContext);
        dialog.setTitle("发现新版本");
        String message = "是否更新到Enterplorer-" + mUpdate.getVersionName();
        View contentView = View.inflate(mContext, R.layout.dialog_update_content, null);
        TextView content = (TextView) contentView.findViewById(R.id.tv_content);
        content.setText(Html.fromHtml(message));
        final CheckBox checkBox = (CheckBox) contentView.findViewById(R.id.cb_ignore);
        String ignoreVersionName = sp.getString(PARAM_IGNORE_UPDATE, "");
        checkBox.setChecked(!TextUtils.isEmpty(ignoreVersionName) && ignoreVersionName.equals(mUpdate.getVersionName()));
        View btnCancel = contentView.findViewById(R.id.btn_cancel);
        View btnUpdate = contentView.findViewById(R.id.btn_update);
        btnUpdate.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
        dialog.setContent(contentView);
        dialog.hideAllButton();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                boolean isChecked = checkBox.isChecked();
                String version = "";
                if (isChecked) {
                    version = mUpdate.getVersionName();
                }
                sp.edit().putString(PARAM_IGNORE_UPDATE, version).apply();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
                    ToastUtils.showToast("SD卡无效，无法下载更新");
                } else {
                    if (TextUtils.isEmpty(mUpdate.getVersionName()) || TextUtils.isEmpty(mUpdate.getDownloadUrl())) {
                        ToastUtils.showToast("无下载链接或对比版本号，联系管理员");
                    } else {
                       // YspDownload.startDownload(mContext, new XDownloadModel(mUpdate.getDownloadUrl(), "中可OA-" + mUpdate.getVersionName() + ".apk"));
                        Intent intent = new Intent(mContext, DownloadAppService.class);
                        intent.setAction("com.putiantaili.service.update");
                        intent.putExtra(EXTRA_DOWNLOAD_APP_VERSION_NAME, mUpdate.getVersionName());
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra(EXTRA_DOWNLOAD_URL, mUpdate.getDownloadUrl());
                        mContext.startService(intent);
                    }
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void showLatestDialog() {
        CommonDialog dialog = DialogHelper.getCancelableCommonDialog(mContext);
        dialog.setTitle("");
        dialog.setMessage("当前已经是最新版本了");
        dialog.hideAllButton();
        dialog.show();
    }

    private void showFailureDialog(String errorMsg) {
        CommonDialog dialog = DialogHelper.getCancelableCommonDialog(mContext);
        dialog.setTitle("");
        dialog.setMessage(TextUtils.isEmpty(errorMsg) ? "网络异常，无法获取新版本信息" : errorMsg);
        dialog.hideAllButton();
        dialog.show();
    }
}
